<template>
  <div class="order-list-container">
    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card stats-primary">
            <div class="stats-content">
              <div class="stats-info">
                <h3>{{ statistics.totalOrders || 0 }}</h3>
                <p>总订单数</p>
              </div>
              <el-icon class="stats-icon" size="48">
                <Box />
              </el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card stats-warning">
            <div class="stats-content">
              <div class="stats-info">
                <h3>{{ statistics.pendingOrders || 0 }}</h3>
                <p>待审批</p>
              </div>
              <el-icon class="stats-icon" size="48">
                <Clock />
              </el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card stats-success">
            <div class="stats-content">
              <div class="stats-info">
                <h3>{{ statistics.approvedOrders || 0 }}</h3>
                <p>已通过</p>
              </div>
              <el-icon class="stats-icon" size="48">
                <Check />
              </el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card stats-danger">
            <div class="stats-content">
              <div class="stats-info">
                <h3>{{ statistics.rejectedOrders || 0 }}</h3>
                <p>已拒绝</p>
              </div>
              <el-icon class="stats-icon" size="48">
                <Close />
              </el-icon>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 操作区域 -->
    <el-card class="operation-card">
      <div class="operation-bar">
        <div class="operation-left">
          <el-button type="primary" @click="showCreateDialog">
            <el-icon><Plus /></el-icon>
            新增订单申请
          </el-button>
          <el-button @click="refreshAll">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
        <div class="operation-right">
          <el-input
            v-model="searchForm.customerName"
            placeholder="搜索客户名称..."
            style="width: 200px; margin-right: 10px;"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-select
            v-model="searchForm.applicationStatus"
            placeholder="全部状态"
            style="width: 120px; margin-right: 10px;"
            clearable
          >
            <el-option label="待审批" value="PENDING" />
            <el-option label="已通过" value="APPROVED" />
            <el-option label="已拒绝" value="REJECTED" />
            <el-option label="已取消" value="CANCELLED" />
          </el-select>
          <el-button type="primary" @click="searchOrders">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="order-list-card">
      <el-table
        :data="orderList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="orderNo" label="订单编号" width="150" />
        <el-table-column prop="customerName" label="客户名称" width="120" />
        <el-table-column prop="productName" label="产品名称" width="200" show-overflow-tooltip />
        <el-table-column prop="quantity" label="数量" width="80" align="center" />
        <el-table-column prop="totalAmount" label="总金额" width="120" align="right">
          <template #default="{ row }">
            ¥{{ row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="applicationStatus" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.applicationStatus)">
              {{ getStatusText(row.applicationStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="currentStep" label="当前步骤" width="120" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewOrderDetail(row)">
              查看详情
            </el-button>
            <!-- 申请人操作按钮 -->
            <el-button
              v-if="row.applicationStatus === 'PENDING' && !row.processInstanceId"
              size="small"
              type="success"
              @click="submitOrder(row.id)"
            >
              提交审批
            </el-button>
            <el-button
              v-if="row.applicationStatus === 'PENDING' && !row.processInstanceId"
              size="small"
              type="warning"
              @click="editOrder(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="row.applicationStatus === 'PENDING' && !row.processInstanceId"
              size="small"
              type="danger"
              @click="cancelOrder(row.id)"
            >
              取消
            </el-button>
            <!-- 审批人操作按钮 -->
            <el-button
              v-if="canApprove(row)"
              size="small"
              type="primary"
              @click="approveOrder(row)"
            >
              通过
            </el-button>
            <el-button
              v-if="canApprove(row)"
              size="small"
              type="danger"
              @click="rejectOrder(row)"
            >
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建订单对话框 -->
    <OrderForm
      v-model:visible="createDialogVisible"
      @success="handleCreateSuccess"
    />

    <!-- 订单详情对话框 -->
    <OrderDetail
      v-model:visible="detailDialogVisible"
      :order="currentOrder"
      @success="handleDetailSuccess"
    />
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Box, Clock, Check, Close, Plus, Refresh, Search
} from '@element-plus/icons-vue'
import { getOrderList, getOrderStatistics, submitOrder, cancelOrder } from '../../api/order.js'
import { queryUserTasks, approveTask, rejectTask } from '../../api/flowable.js'
import OrderForm from './OrderForm.vue'
import OrderDetail from './OrderDetail.vue'

export default {
  name: 'OrderList',
  components: {
    Box, Clock, Check, Close, Plus, Refresh, Search,
    OrderForm,
    OrderDetail
  },
  setup() {
    const loading = ref(false)
    const orderList = ref([])
    const statistics = ref({})
    const createDialogVisible = ref(false)
    const detailDialogVisible = ref(false)
    const currentOrder = ref(null)
    
    const searchForm = reactive({
      customerName: '',
      applicationStatus: ''
    })
    
    const pagination = reactive({
      current: 1,
      size: 10,
      total: 0
    })
    
    // 加载订单列表
    const loadOrders = async () => {
      try {
        loading.value = true
        const params = {
          page: pagination.current - 1,
          size: pagination.size,
          ...searchForm
        }
        
        const response = await getOrderList(params)
        orderList.value = response.content || []
        pagination.total = response.totalElements || 0
      } catch (error) {
        console.error('加载订单列表失败:', error)
        ElMessage.error('加载订单列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 加载统计信息
    const loadStatistics = async () => {
      try {
        const response = await getOrderStatistics()
        statistics.value = response
      } catch (error) {
        console.error('加载统计信息失败:', error)
      }
    }
    
    // 搜索订单
    const searchOrders = () => {
      pagination.current = 1
      loadOrders()
    }
    
    // 刷新所有数据
    const refreshAll = async () => {
      try {
        loading.value = true
        ElMessage.info('正在刷新数据...')
        
        // 并行加载所有数据
        await Promise.all([
          loadOrders(),
          loadStatistics(),
          loadUserTasks()
        ])
        
        ElMessage.success('数据刷新成功')
      } catch (error) {
        console.error('刷新数据失败:', error)
        ElMessage.error('刷新数据失败')
      } finally {
        loading.value = false
      }
    }
    
    // 分页大小改变
    const handleSizeChange = (val) => {
      pagination.size = val
      pagination.current = 1
      loadOrders()
    }
    
    // 当前页改变
    const handleCurrentChange = (val) => {
      pagination.current = val
      loadOrders()
    }
    
    // 显示创建对话框
    const showCreateDialog = () => {
      createDialogVisible.value = true
    }
    
    // 查看订单详情
    const viewOrderDetail = (order) => {
      currentOrder.value = order
      detailDialogVisible.value = true
    }
    
    // 编辑订单
    const editOrder = (order) => {
      currentOrder.value = order
      createDialogVisible.value = true
    }
    
    // 提交订单审批
    const submitOrderConfirm = async (orderId) => {
      try {
        await submitOrder(orderId)
        ElMessage.success('订单提交成功，已启动审批流程')
        loadOrders()
        loadStatistics()
      } catch (error) {
        console.error('提交订单失败:', error)
        ElMessage.error('提交订单失败')
      }
    }
    
    // 取消订单
    const cancelOrderConfirm = async (orderId) => {
      try {
        const { value: reason } = await ElMessageBox.prompt('请输入取消原因：', '取消订单', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /.+/,
          inputErrorMessage: '取消原因不能为空'
        })
        
        await cancelOrder(orderId, reason)
        ElMessage.success('订单已取消')
        loadOrders()
        loadStatistics()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消订单失败:', error)
          ElMessage.error('取消订单失败')
        }
      }
    }
    
    // 获取状态类型
    const getStatusType = (status) => {
      const statusMap = {
        'PENDING': 'warning',
        'APPROVED': 'success',
        'REJECTED': 'danger',
        'CANCELLED': 'info'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'PENDING': '待审批',
        'APPROVED': '已通过',
        'REJECTED': '已拒绝',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || status
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '-'
      return new Date(dateString).toLocaleString()
    }
    
    // 创建成功回调
    const handleCreateSuccess = () => {
      refreshAll()
    }
    
    // 详情操作成功回调
    const handleDetailSuccess = () => {
      refreshAll()
    }
    
    // 获取当前登录用户
    const getCurrentUser = () => {
      const userInfoStr = localStorage.getItem('userInfo')
      if (userInfoStr) {
        return JSON.parse(userInfoStr)
      }
      return null
    }
    
    // 待办任务列表（存储当前用户的待办任务）
    const userTasks = ref([])
    
    // 加载用户待办任务
    const loadUserTasks = async () => {
      try {
        const user = getCurrentUser()
        if (user && user.username) {
          const response = await queryUserTasks(user.username)
          if (response && response.success) {
            userTasks.value = response.data || []
            console.log('待办任务加载成功，任务数量:', userTasks.value.length)
          } else {
            console.warn('待办任务加载失败，响应:', response)
            userTasks.value = []
          }
        } else {
          console.warn('用户信息不完整，无法加载待办任务')
          userTasks.value = []
        }
      } catch (error) {
        console.error('加载待办任务失败:', error)
        userTasks.value = []
        // 在刷新时显示错误信息
        if (loading.value) {
          ElMessage.warning('待办任务加载失败，请稍后重试')
        }
      }
    }
    
    // 判断当前用户是否可以审批该订单
    const canApprove = (order) => {
      // 订单必须已提交审批（有processInstanceId）且状态为APPROVING
      if (!order.processInstanceId || order.applicationStatus !== 'APPROVING') {
        return false
      }
      
      // 检查当前用户是否有该订单的待办任务
      const user = getCurrentUser()
      if (!user || !user.username) {
        return false
      }
      
      // 办事处商务不应该看到审批按钮，他们只负责发起审批
      if (user.role === '办事处商务' || user.role === 'office_business') {
        return false
      }
      
      // 查找是否有对应该订单的待办任务
      const hasTask = userTasks.value.some(task => {
        // 通过processInstanceId匹配任务
        return task.processInstanceId === order.processInstanceId
      })
      
      return hasTask
    }
    
    // 审批通过
    const approveOrder = async (order) => {
      try {
        // 找到对应的任务
        const task = userTasks.value.find(t => t.processInstanceId === order.processInstanceId)
        if (!task) {
          ElMessage.error('未找到对应的审批任务')
          return
        }
        
        await ElMessageBox.confirm('确认通过该订单申请吗？', '确认审批', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        })
        
        await approveTask(task.taskId)
        ElMessage.success('审批通过')
        
        // 等待一下让流程完成
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 刷新所有数据
        await refreshAll()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('审批失败:', error)
          ElMessage.error('审批失败')
        }
      }
    }
    
    // 审批拒绝
    const rejectOrder = async (order) => {
      try {
        // 找到对应的任务
        const task = userTasks.value.find(t => t.processInstanceId === order.processInstanceId)
        if (!task) {
          ElMessage.error('未找到对应的审批任务')
          return
        }
        
        const { value: reason } = await ElMessageBox.prompt('请输入拒绝原因：', '拒绝审批', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /.+/,
          inputErrorMessage: '拒绝原因不能为空'
        })
        
        await rejectTask(task.taskId, reason)
        ElMessage.success('已拒绝该申请')
        
        // 等待一下让流程完成
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 刷新所有数据
        await refreshAll()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('拒绝失败:', error)
          ElMessage.error('拒绝失败')
        }
      }
    }
    
    
    onMounted(async () => {
      loadStatistics()
      loadOrders()
      
      // 延迟加载待办任务，确保用户信息已经加载
      setTimeout(() => {
        loadUserTasks()
      }, 100)
    })
    
    return {
      loading,
      orderList,
      statistics,
      searchForm,
      pagination,
      createDialogVisible,
      detailDialogVisible,
      currentOrder,
      userTasks,
      loadOrders,
      loadStatistics,
      loadUserTasks,
      searchOrders,
      refreshAll,
      handleSizeChange,
      handleCurrentChange,
      showCreateDialog,
      viewOrderDetail,
      editOrder,
      submitOrder: submitOrderConfirm,
      cancelOrder: cancelOrderConfirm,
      canApprove,
      approveOrder,
      rejectOrder,
      getStatusType,
      getStatusText,
      formatDate,
      handleCreateSuccess,
      handleDetailSuccess
    }
  }
}
</script>

<style scoped>
.order-list-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 60px);
}

.stats-cards {
  margin-bottom: 20px;
}

.stats-card {
  border: none;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.stats-card:hover {
  transform: translateY(-2px);
}

.stats-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: white;
}

.stats-info h4 {
  margin: 0 0 5px 0;
  font-size: 2rem;
  font-weight: bold;
}

.stats-info p {
  margin: 0;
  font-size: 0.9rem;
  opacity: 0.9;
}

.stats-icon {
  font-size: 3rem;
  opacity: 0.8;
}

.stats-primary {
  background: linear-gradient(135deg, #409EFF, #66b1ff);
}

.stats-warning {
  background: linear-gradient(135deg, #E6A23C, #f0c78a);
}

.stats-success {
  background: linear-gradient(135deg, #67C23A, #95d475);
}

.stats-danger {
  background: linear-gradient(135deg, #F56C6C, #f89898);
}

.operation-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.operation-left {
  display: flex;
  gap: 10px;
}

.operation-right {
  display: flex;
  align-items: center;
}

.order-list-card {
  min-height: 400px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.table th {
  background-color: #343a40;
  color: white;
  border: none;
  font-weight: 500;
}

.table td {
  vertical-align: middle;
  border-color: #dee2e6;
}

.table-hover tbody tr:hover {
  background-color: #f8f9fa;
}

.badge {
  font-size: 0.75em;
  padding: 0.375rem 0.75rem;
}

.me-1 {
  margin-right: 0.25rem;
}

.spinner-border {
  width: 2rem;
  height: 2rem;
}

@media (max-width: 768px) {
  .operation-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .operation-left,
  .operation-right {
    justify-content: center;
  }
  
  .table-responsive {
    font-size: 0.875rem;
  }
}
</style>
